<?php

namespace app\common\command\task;

use app\common\model\AnswerQuestion;
use app\common\service\UserExtendService;
use app\common\service\UserService;

/**
 *
 * php think cron userRank
 */
class UserRanking
{
    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        // 查询活跃用户
        $userService = app(UserService::class);
        $userList = $userService->getActiveUsers(3);
        foreach ($userList as $user) {
            // 更新用户答题数
            try {
                $this->execute($user);
            } catch (\Exception $e) {
                dump($e->getMessage());
                echo '更新用户' . $user['id'] . '数据失败' . PHP_EOL;
            }
        }
    }

    /**
     * execute
     * @param $user
     * @return void
     * @throws \think\db\exception\DbException
     */
    private function execute($user)
    {
        // 查询条件
        $where = [
            ['user_id', '=', $user['id']]
        ];

        // 查询答题次数
        $answerModel = new AnswerQuestion();
        $count = $answerModel->where($where)->count();

        // 更新用户数据
        $userExtendService = app(UserExtendService::class);
        $userExtendService->saveDataByField($user['id'], 'number_of_answers', $count);
        $where = [
            ['uid', '=', $user['id']]
        ];
        $saveData = [
            'number_of_answers' => $count,
            'update_time' => $user['update_time'],
        ];
        $userExtendService->saveData($saveData, $where);
    }
}